#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

PARA_ITEM_DLM=$'\xff'
(( PARA_ITEM_SIZE_CHAR=5 ))
(( PARA_ITEM_MAX_SIZE=(1<<(PARA_ITEM_SIZE_CHAR * BIT_OF_CHAR / 2)) - 1 ))

para_item_size()
{ #[[[
    local item_size
    (( item_size=PARA_ITEM_SIZE_CHAR+1+${#1}+1 ))
    echo $item_size
} #]]]

para_put_item()
{ #[[[
    local msg=$1
    shift
    local item
    for item in "$@"
    do
        msg=${msg}$(printf '%05X' ${#item})${PARA_ITEM_DLM}${item}${PARA_ITEM_DLM}
    done
    echo $msg
} #]]]

para_get_item()
{ #[[[
    local msg=$1
    local curr
    (( curr=$2 ))

    local left_size
    (( left_size=${#msg}-curr ))
    if (( left_size < PARA_ITEM_SIZE_CHAR+1+1 ))
    then echo ''; return 1; fi
    (( item_pos=curr+PARA_ITEM_SIZE_CHAR+1 ))
    if [[ ${msg:item_pos-1:1} != $PARA_ITEM_DLM ]]
    then echo ''; return 1; fi
    local item_size
    (( item_size=0x${msg:curr:PARA_ITEM_SIZE_CHAR} ))
    if (( item_size < 0 || item_size > left_size-PARA_ITEM_SIZE_CHAR-1-1 ))
    then echo ''; return 1; fi
    if [[ ${msg:item_pos+item_size:1} != $PARA_ITEM_DLM ]]
    then echo ''; return 1; fi
    echo ${msg:item_pos:item_size}
} #]]]
